package com.ssr.master.controller.sys;

import com.ssr.master.common.utils.RedisUtil;
import com.ssr.master.common.utils.RequestUtils;
import com.ssr.master.common.utils.StringUtils;
import com.ssr.master.common.utils.UserUtil;
import com.ssr.master.modules.entity.SysMenuDict;
import com.ssr.master.modules.entity.SysUser;
import com.ssr.master.modules.service.SysMenuDictService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ZhangPeng
 * @Describe //todo  登录controller
 * @date
 * @updateBy
 * @other
 **/

@Controller
@RequestMapping("/a")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysMenuDictService sysMenuDictService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @param
     * @return java.lang.String
     * @Description //todo 系统登录页面（欢迎页面）
     * @author ZhangPeng
     * @date 2020/6/20 21:58
     * @other
     **/
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        SysUser sysUser = UserUtil.getUser();
        if (StringUtils.isNotBlank(sysUser.getLoginName())) {
            // 查询用户菜单列表列表
            List<SysMenuDict> list = sysMenuDictService.getParentList(sysUser.getId());
            request.setAttribute("menuList", list);
            request.setAttribute("username", sysUser.getLoginName());
            request.setAttribute("exception", "");
            redisUtil.set("sysUser" + sysUser.getId(), sysUser);
            return "index";
        } else {
            return "login";
        }
    }

    /**
     * @param username
     * @param password
     * @param request
     * @return java.lang.String
     * @Description //todo 登录成功跳转页面
     * @author ZhangPeng
     * @date 2020/6/20 21:58
     * @other
     **/
//    @RequiresPermissions("user")
    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public String submitLogin(String username, String password, HttpServletRequest request) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            subject.login(token);
            // 执行到这里说明用户已登录成功
            return "redirect:/a/index";
        } catch (Exception e) {
            logger.error("登录失败，用户名[{}]", username, e);
            String exception = e.toString();
            request.setAttribute("userName", username);
            request.setAttribute("exception", StringUtils.subStringAppoint(":",exception));
            token.clear();
            return "login";
        }
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String loginSuccessMessage(HttpServletRequest request) {
        String username = "未登录";
        RequestUtils requestUtils = new RequestUtils();
        SysUser currentLoginUser = requestUtils.currentLoginUser();
        if (currentLoginUser != null && StringUtils.isNotEmpty(currentLoginUser.getLoginName())) {
            username = currentLoginUser.getLoginName();
        } else {
            return "redirect:/a/login";
        }
        // 查询用户菜单列表列表
        List<SysMenuDict> list = sysMenuDictService.getParentList(currentLoginUser.getId());
        request.setAttribute("menuList", list);
        request.setAttribute("username", username);
        request.setAttribute("exception", "");
        return "index";
    }

    /**
     * @param
     * @return java.lang.String
     * @Description //todo 被踢出后跳转的页面
     * @author ZhangPeng
     * @date 2020/6/20 22:08
     * @other
     **/
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String kickOut() {
        SysUser sysUser = UserUtil.getUser();
        redisUtil.del("sysUser" + sysUser.getId());
        // 此处有坑： 退出登录，其实不用实现任何东西，只需要保留这个接口即可，也不可能通过下方的代码进行退出
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:/a/login";
    }
}
